from prg.common.object_message import MessageBase


class UdpReceive(MessageBase):
    def __init__(self, socket_item, bytes_array):
        super().__init__(name="udp_rec")
        self.socket_item = socket_item
        self.bytes_array = bytes_array
        self.read_max = None
        self.addr = None
        self.ready = False

    def run_receive(self, addr, read_max=1024):
        self.semaphore_item = None
        self.addr = addr
        self.read_max = read_max
        self.start()

    def read_run(self):
        link_inf = (str(self.socket_item.getsockname()), str(self.socket_item.getpeername()))
        print("read socket name: %s, peer name:%s" % link_inf)
        with self.socket_item as socket_item:
            while self.is_run():
                try:
                    read_byte_tmp, read_addr_tmp = socket_item.recvfrom(self.read_max)
                except Exception as e:
                    print("read data error: %s" % e)
                    break
                else:
                    if self.addr != read_addr_tmp:
                        raise Exception("Invalid Address")
                    self.bytes_array.append(read_byte_tmp)

    def entry(self):
        self.read_run()





